﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WomanMotion.WebApi.Infrastructure.DataBaseCommon;
using WomanMotion.WebApi.Model.Dtos.Classify;
using WomanMotion.WebApi.Model.Dtos.Comment;
using WomanMotion.WebApi.Model.Entitys;
using WomanMotion.WebApi.Repository.IRepository;
using WomanMotion.WebApi.Repository.Repository;
using WomanMotion.WebApi.Service.IService;

namespace WomanMotion.WebApi.Service.Service
{
    public class CommentService : BaseCRUDService<Comment, CommentVM, UpdateCommentDTO, CreatedCommentDTO>, ICommentService
    {
        private readonly ICommentRepository _commentRepository;

        public CommentService(ILogger<CommentService> logger, IMapper mapper, ICommentRepository commentRepository, IHttpContextAccessor httpContext) : base(logger, mapper, commentRepository, httpContext)
        {
            _commentRepository = commentRepository;
        }

        /// <summary>
        ///根据当前评论ID查询出所属下一级的评论
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<List<CommentPageVM>> GetByParentIdAsync(long id)
        {
            var res = await this._commentRepository.GetCommonListAsync<CommentPageVM>(_commentRepository.GetDB().Queryable<Comment>()
                .LeftJoin<Users>((st, usercr) => st.Createdby == usercr.Id)
                .LeftJoin<Users>((st, usercr, userup) => st.Updatedby == userup.Id)
                .InnerJoin<Contents>((st, usercr, userup, cont) => st.Contentsid == cont.Id)
                .LeftJoin<Comment>((st, usercr, userup, cont, Parent) => st.Parentid == Parent.Id)
                .Select((st, usercr, userup, cont, Parent) =>
            new CommentPageVM()
            {
                Id = st.Id,
                Contentsid = st.Contentsid,
                Parentid = st.Parentid,
                ParentContent = Parent.Content,
                ContentsTitle = cont.Title,
                Content = st.Content,
                Createdby = st.Createdby,
                CreatedName = usercr.Name,
                Createdtime = st.Createdtime,
                Updatedby = st.Updatedby,
                UpdatedName = userup.Name,
                Updatedtime = st.Updatedtime,
                Ifdisable = st.Ifdisable
            }).MergeTable().Where(m => m.Parentid == id));
            return res;
        }

        /// <summary>
        /// 返回前端tree控件的评论数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        public async Task<CommentTreeListVM> GetTreeByIdAsync(long id)
        {
            //获取userid
            long userid = 0;
            //当HttpContext等于null的时候说明是系统初始化直接取admin的id
            if (httpContext.HttpContext == null)
            {
                userid = 0;
            }
            else
            {
                try
                {
                    userid = long.Parse(httpContext.HttpContext.User.Claims.Where(m => m.Type == "UserId").First().Value);
                }
                catch (Exception ex)
                {
                    userid = 0;
                }
            }
            var res = new CommentTreeListVM();
            res.readNumer = 0;
            //获取文章的所有评论数据
            var commentlist = await _commentRepository.GetListNavAsync(m => m.Contentsid == id && m.Ifdisable == 1);
            if (commentlist == null || commentlist.Count <= 0)
            {
                res.commentList = null;
                return res;
            }
            var commentTreeList = new List<CommentTreeVM>();
            foreach (var comment in commentlist)
            {
                var commentTree = new CommentTreeVM();
                commentTree.id = comment.Id;
                //是否为创建者
                if (comment.Createdby == userid)
                {
                    commentTree.owner = true;
                }
                else
                {
                    commentTree.owner = false;
                }
                commentTree.hasLike = false;
                commentTree.likeNum = 0;
                commentTree.avatarUrl = comment.CreatedUsers.Photo;
                commentTree.nickName = comment.CreatedUsers.Name;
                commentTree.content = comment.Content;
                commentTree.parentId = comment.Parentid;
                commentTree.createTime = comment.Createdtime.ToString("yyyy-MM-dd HH:mm:ss");
                commentTreeList.Add(commentTree);
            }
            res.commentList = commentTreeList;
            return res;
        }
    }
}